// import { isWeChatBrowser } from '@/config/h5/index.js'
import API from '@/services/h5/login'
import { ls } from '@/utils/aes'
import { setAuthorization } from '@/utils/request'
import { mapMutations, mapState } from 'vuex'
export default {
  computed: {
    ...mapState('loading', ['loading'])
  },
  data() {
    return {
      openId: '',
      params: null,
      uuid_key: null,
      loginType: 'validatecode'
    }
  },
  methods: {
    ...mapMutations('account', ['setUser']),
    ...mapMutations('loading', ['setLoading']),
    getWXCode() {
      this.setLoading(true)
      //获取地址栏url
      let searchParams = window.location.search
      if (searchParams.indexOf('?') > -1) {
        let queryList = searchParams.split('?')[1].split('&')
        let params = {}
        queryList.map(item => {
          let itemObj = item.split('=')
          if (itemObj[0]) {
            params[itemObj[0]] = itemObj[1]
          }
        })
        //获取到code和state的值
        this.params = params
        //如果是微信浏览器和code值存在的情况
        if (params.code) {
          //仅微信端使用code登录
          API.wxloginCode(params).then(res => {
            this.setLoading(false)
            if (res.data && res.data.code === 1000) {
              const accesstoken = res.headers['access-token']
              if (accesstoken) {
                this.setUserInfo(res)
              }
              if (res.data.data.openId) {
                this.openId = res.data.data.openId
                localStorage.setItem('openId', this.openId)
                this.$router.replace('/home')
              }
            }
          })
          this.setLoading(false)
        }
      } else {
        this.setLoading(false)
      }
    },
    async wxLogin(values) {
      let data = localStorage.getItem('openId')
        ? localStorage.getItem('openId')
        : ''
      if (this.loginType === 'password') {
        let params = {
          ...values,
          openId: this.openId || data
        }
        API.wxloginByPsd(params).then(this.setUserInfo)
      }
      if (this.loginType === 'validatecode') {
        let params = {
          ...values,
          openId: this.openId || data
        }
        API.wxloginByMsg(params).then(this.setUserInfo)
      }
    },
    setUserInfo(res) {
      let user = {}
      const accesstoken = res.headers['access-token']
      const expireAt = new Date(new Date().getTime() + 24 * 60 * 60 * 1000)
      if (res.data.code === 1000) {
        setAuthorization({
          token: accesstoken,
          expireAt: new Date(expireAt)
        })
        user.refreshtoken = res.headers['refresh-token']
        this.setUser(user)
        ls.set('loginKey', res.headers['public-key'])
        localStorage.setItem('unloginKey', res.headers['public-key'])
        localStorage.setItem('refreshToken', res.headers['refresh-token'])
        this.$router.replace('/home')
        this.setLoading(false)
      }
    }
  }
}
